#include "MultiColumnFilterProxyModel.h"

class MultiColumnFilterProxyModelPrivate
{
    Q_DISABLE_COPY(MultiColumnFilterProxyModelPrivate)
    Q_DECLARE_PUBLIC(MultiColumnFilterProxyModel)
    MultiColumnFilterProxyModel * const q_ptr;

    explicit MultiColumnFilterProxyModelPrivate(MultiColumnFilterProxyModel *model):
        q_ptr(model)
    {}

    QList<int> filterKeyColumns;
};

MultiColumnFilterProxyModel::MultiColumnFilterProxyModel(QObject *parent):
    QSortFilterProxyModel(parent),
    d_ptr(new MultiColumnFilterProxyModelPrivate(this))
{

}

MultiColumnFilterProxyModel::~MultiColumnFilterProxyModel()
{

}

QList<int> MultiColumnFilterProxyModel::filterKeyColumns() const
{
    Q_D(const MultiColumnFilterProxyModel);
    return d->filterKeyColumns;
}

void MultiColumnFilterProxyModel::setFilterKeyColumns(QList<int> columns)
{
    Q_D(MultiColumnFilterProxyModel);

    if (d->filterKeyColumns == columns)
        return;

    d->filterKeyColumns = columns;
    invalidateFilter();
}

void MultiColumnFilterProxyModel::setFilterKeyColumns(int first, int last)
{
    QList<int> columns;
    for (int column = first; column <= last; column++)
        columns.append(column);
    setFilterKeyColumns(columns);
}

bool MultiColumnFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    Q_D(const MultiColumnFilterProxyModel);

    if (d->filterKeyColumns.isEmpty())
        return true;

    for (int column: d->filterKeyColumns)
    {
        const QModelIndex index = sourceModel()->index(sourceRow, column, sourceParent);
        const QString text = index.data(filterRole()).toString();
        if (filterRegExp().indexIn(text) >= 0)
            return true;
    }
    return false;
}
